﻿/**
 * Created by wzj on 2017/3/20.
 */

/**
 * 表格
 *
 * <BootstrapTable>
 * 		data={ products } 数据
 * 		bordered={false} 边框
 * 		striped 各行色
 * 		hover 鼠标停留色
 * 	 	height='120' 出滚动条 scrollTop={ 'Bottom' }滚动置底部 top/bottom/ 任一数字
 *
 * <TableHeaderColumn>
 *  	width='150'
 *  	dataField='id'
 *  	isKey
 *
 *  	dataAlign='center'	//数据单元格对齐方式
 *  	headerAlign='right'	//表头单元格对齐方式
 *
 *  	width='150'
 *  	hidden	//隐藏
 *
 *  	tdStyle={ { whiteSpace: 'normal' } }
 *
 *  	dataFormat={ priceFormatter } 数据格式化
 *  	function priceFormatter(cell, row) { return "";}
 *
 *
 *
 *
 *
 *
 */


/*--------------------------------------------------------------------------------------------*/

var products = [];
function addProducts() {
	const startId = products.length;
	for (var i = 0; i < 50; i++) {
		const id = startId + i;
		products.push({
			id: id,
			name: 'Item name ' + id,
			price: 2100 + i
		});
	}
}
addProducts();
/*--------------------------------------------------------------------------------------------*/
//
class RTable extends React.Component {

	constructor(props) {
		super(props);
		//初始数据
		this.products = products;
		this.state = {
			datas:[],
			totalSize: 0,
			sizePerPage: 5,
			page: 1
		}


		//数据行选中配置
		this.selectRowProp  = {
			mode: 'radio',
			onSelect: this.onRowSelect,
			onSelectAll: this.onSelectAll
		}

		this.ajaxRequestData = this.ajaxRequestData.bind(this);
		this.handlePageChange = this.handlePageChange.bind(this);
		this.handleSizePerPageChange = this.handleSizePerPageChange.bind(this);

	}
	/*******************************************************************/
	//DOM加载完成
	componentDidMount(){
		//请求第1页数据，且每页显示5条
		alert(12);
		this.ajaxRequestData();
	}
	/*******************************************************************/

	ajaxRequestData(page = this.state.page, sizePerPage = this.state.sizePerPage) {
		alert("请求第" + page + "页数据，每页显示" + sizePerPage);

		const currentIndex = (page - 1) * sizePerPage;
		this.setState({
			datas: products.slice(currentIndex, currentIndex + sizePerPage),
			totalSize: products.length,
			page:page,
			sizePerPage:sizePerPage
		})


		//ajax加载数据
		
		$.ajax({
			url:this.props.url,
			data:this.props.data,
			type:'post',
			success:function(str,msg,response){
				if(response.statusText=="success"){
					var result = JSON.parse(response.responseText);
					this.setState({
						datas:products
					});

				}
			}.bind(this),
			error:function(str,msg,response){

			}.bind(this)
		});
		
	}
	/*******************************************************************/

	//分页数量选项事件
	handleSizePerPageChange(sizePerPage){
		this.ajaxRequestData(1, sizePerPage);
	}

	//分页事件
	handlePageChange(page, sizePerPage){
		this.ajaxRequestData(page,sizePerPage);
	}

	/*******************************************************************/
	//选中行
	onRowSelect = (row, isSelected) =>{
		var rowArr = [];
		if(isSelected) {
			rowArr.push(row.id);
		}
	}
	onSelectAll = (isSelected, currentDisplayAndSelectedData) =>{

	}

	/*******************************************************************/
	//外部模态窗体表单保存
	externalModalOnSave	= (object) =>{
		alert("添加"+object)
		alert(11);
		var dt= new Date().getTime();
		//var ddt= new Date().formdt("yyyy-MM-dd");
	var rt=	new RTable();
	//SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		var props={url:"",data:""};
		props.url="http://localhost:8080/lqueryMemberInOutMoneyFlow";
		props.data=object+"&tranFunc=1021&counterId=69530&qydm=9012&servType=01&tranDate="+formatDate(new Date())+"&thirdLogNo="+new Date().getTime();//"&tranFunc=1021&tranDate="+formatDate(new Date());//+"&thirdLogNo="+new Date().getTime();//"&tranFunc=1021&counterId=69530&qydm=9012&servType=01&tranDate="+formatDate(new Date())+"&thirdLogNo="+new Date().getTime();//"supAcctId=1&paySerialNo=6";
		rt.constructor(props);
		rt.componentDidMount();
		
	}
	//自定义添加按钮点击事件
	handleInsertButtonClick = (onClick) => {
		//console.log(onClick,this);
		showExternalModalForm();
		//onClick(); //弹出自带模态窗体
	}
	//自定义添加按钮
	createCustomInsertButton =(onClick) =>{
		return (
			<button className="btn btn-primary" onClick={ () => this.handleInsertButtonClick(onClick) }>+添加</button>
			//<button className="btn btn-primary" onClick={ openModal }>+添加</button>
		);
	}

	//自定义删除按钮点击事件
	handleDeleteButtonClick = (onClick) => {
		alert("删除id:"+this.state.selectRows)
	}
	//自定义删除按钮
	createCustomDeleteButton = (onClick) => {
		return (
			<button className="btn btn-danger" onClick={ e => this.handleDeleteButtonClick(onClick) }>-删除</button>
			//<button className="btn btn-danger" onClick={ onBtnClick }>-删除</button>
		);
	}
	/*******************************************************************/
	//过滤按钮事件
	handleBtnClick = (evt) =>{
		var value = evt.target.innerHTML;
	//	this.refs.filterName.applyFilter(value);
		alert("过滤Name:"+value)
	}

	//过滤下拉框事件
	handleSelectChange = (evt) =>{
		var value = evt.target.options[evt.target.options.selectedIndex].value;
		//this.refs.filterName.applyFilter(value);

		alert("过滤Name:"+value)
	}

	/*******************************************************************/
	render() {

	//配置
	const tableOptions = {
		noDataText: '暂无可用数据',

		page: this.state.page,		//当前第几页
		sizePerPage: this.state.sizePerPage,	//每页显示几条
		onPageChange: this.handlePageChange,  //分页事件
		onSizePerPageList: this.handleSizePerPageChange, //分页下拉事件

		sizePerPageList: [
			{text: '5', value: 5},
			{text: '10', value: 10 },
			{text:'所有', value:this.products.length}
		],				//分页数量选项
		sizePerPage: this.state.sizePerPage,	//每页显示条数
		pageStartIndex: this.state.currentPage, //	分页开始索引
		paginationSize: 3,	//分页数字按钮个数
		prePage: '上一页',
		nextPage: '下一页',
		firstPage: '首页',
		lastPage: '尾页'
		,insertBtn: this.createCustomInsertButton		//自定义添加按钮
		,deleteBtn: this.createCustomDeleteButton		//自定义删除按钮
		,insertModalBody: this.createCustomModalBody	//自定义模态窗窗体
		,insertModalHeader: this.createCustomModalHeader	//自定义模态窗标题
		,onAddRow: this.onAddNewRow	//远程添加新数据
		,onDeleteRow: this.onDeleteRow	//远程删除数据
	}

		return (
			<div>
				<p>
					过滤条件:
					<button onClick={ this.handleBtnClick } className='btn btn-default'>1</button>
					<button onClick={ this.handleBtnClick } className='btn btn-default'>2</button>
					<select onChange={ this.handleSelectChange  }>
						<option value="">所有</option>
						<option value="1">1</option>
						<option value="2">2</option>
					</select>
				</p>
				<BootstrapTable data={ this.state.datas }
								remote={true}
								striped hover

								fetchInfo={ { dataTotalSize: this.state.totalSize } }

								options={ tableOptions }
								pagination={ true }
								insertRow={true}
								deleteRow={ true }
								selectRow={ this.selectRowProp }
								>
				<TableHeaderColumn dataField='id'  isKey={ true } hiddenOnInsert={false}>ID</TableHeaderColumn>
				<TableHeaderColumn dataField='name'  ref='filterName' filter={ { type: 'TextFilter', delay: 1000 } }>Name</TableHeaderColumn>
				<TableHeaderColumn dataField='price' dataFormat={customFormatterPrice} >Price </TableHeaderColumn>
				</BootstrapTable>
			</div>
		);
	}
}
var myRTable = ReactDOM.render(<RTable url="" />,document.getElementById("component-table"));



//自定义格式化表格内容
function customFormatterPrice(cell,row){
	return "$ "+cell;
}
//保存表单数据
function save_newItem(){
	//调用组件内保存方法并发送ajax请求
	myRTable.externalModalOnSave($("#item-form").serialize());
}
//显示外部模态窗体
function showExternalModalForm(){
	$("#modal-itemForm").modal("show");
}


function formdt(fmt) { 
    var o = { 
       "M+" : this.getMonth()+1,                 //月份 
       "d+" : this.getDate(),                    //日 
       "h+" : this.getHours(),                   //小时 
       "m+" : this.getMinutes(),                 //分 
       "s+" : this.getSeconds(),                 //秒 
       "q+" : Math.floor((this.getMonth()+3)/3), //季度 
       "S"  : this.getMilliseconds()             //毫秒 
   }; 
   if(/(y+)/.test(fmt)) {
           fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
   }
    for(var k in o) {
       if(new RegExp("("+ k +")").test(fmt)){
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
        }
    }
   return fmt; 
} 

var formatDate = function (date) {  
    var y = date.getFullYear();  
    var m = date.getMonth() + 1;  
    m = m < 10 ? '0' + m : m;  
    var d = date.getDate();  
    d = d < 10 ? ('0' + d) : d;  
    return y + m +  d;  
};  
